/* 
    创建贴吧
*/

import { SchemaFactory, Prop, Schema } from '@nestjs/mongoose'
import mongoose, { Document } from 'mongoose'
import { Proposition } from './proposition.schema'
import { SubBar } from './subBar.schema'
export type BarDocument = Bar & Document

@Schema({ timestamps: true })
class Bar {
  @Prop({ required: true })
  barName: string
  //贴吧描述
  @Prop({ required: true })
  description: string
  //贴吧头像
  @Prop({ required: true })
  barLogo: string
  //创建者(吧主)
  @Prop({ required: true, ref: 'User' })
  creator: mongoose.Types.ObjectId
  //被关注
  @Prop({ default: 0 })
  beSubCount: number
  //帖子数量
  @Prop({ default: 0 })
  propositionCount: number
  //是否被关注
  @Prop({ default: false })
  isSub: boolean
}

const BarSchema = SchemaFactory.createForClass(Bar)

BarSchema.pre('remove', async function () {
  const result = await this.$model(Proposition.name).find({ bar: this._id.toString() })

  result.forEach(async (doc) => {
    await doc.remove()
  })

  const sub = await this.$model(SubBar.name).find({ bar: this._id.toString() })
  sub.forEach(async (doc) => {
    await doc.remove()
  })
})

// BarSchema.pre('deleteOne', function (next) {
//   console.log('delete')
// })
export { BarSchema, Bar }
